<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=iso-8859-1">
<title>Using the JMS API in a Java EE Application - The Java EE 5 Tutorial</title>
<meta name="robots" content="index,follow">
<meta name="robots" content="index,follow">
<meta name="date" content="2008-10-01">
<link rel="stylesheet" type="text/css" href="css/default.css">
<link rel="stylesheet" type="text/css" href="css/ipg.css">
<link rel="stylesheet" type="text/css" href="css/j5eetutorial.css">
</head>

<body>

<table border="0" cellpadding="5" cellspacing="0" width="100%">
<tbody>
   <tr valign="top">
      <td><p class="toc level1"><a href="docinfo.html">Document Information</a></p>
<p class="toc level1 tocsp"><a href="gexaf.html">Preface</a></p>
<p class="toc level1 tocsp"><a href="gfirp.html">Part&nbsp;I&nbsp;Introduction</a></p>
<p class="toc level2"><a href="bnaaw.html">1.&nbsp;&nbsp;Overview</a></p>
<p class="toc level2"><a href="gfiud.html">2.&nbsp;&nbsp;Using the Tutorial Examples</a></p>
<p class="toc level1 tocsp"><a href="bnadp.html">Part&nbsp;II&nbsp;The Web Tier</a></p>
<p class="toc level2"><a href="bnadr.html">3.&nbsp;&nbsp;Getting Started with Web Applications</a></p>
<p class="toc level2"><a href="bnafd.html">4.&nbsp;&nbsp;Java Servlet Technology</a></p>
<p class="toc level2"><a href="bnagx.html">5.&nbsp;&nbsp;JavaServer Pages Technology</a></p>
<p class="toc level2"><a href="bnajo.html">6.&nbsp;&nbsp;JavaServer Pages Documents</a></p>
<p class="toc level2"><a href="bnakc.html">7.&nbsp;&nbsp;JavaServer Pages Standard Tag Library</a></p>
<p class="toc level2"><a href="bnalj.html">8.&nbsp;&nbsp;Custom Tags in JSP Pages</a></p>
<p class="toc level2"><a href="bnaon.html">9.&nbsp;&nbsp;Scripting in JSP Pages</a></p>
<p class="toc level2"><a href="bnaph.html">10.&nbsp;&nbsp;JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnaqz.html">11.&nbsp;&nbsp;Using JavaServer Faces Technology in JSP Pages</a></p>
<p class="toc level2"><a href="bnatx.html">12.&nbsp;&nbsp;Developing with JavaServer Faces Technology</a></p>
<p class="toc level2"><a href="bnavg.html">13.&nbsp;&nbsp;Creating Custom UI Components</a></p>
<p class="toc level2"><a href="bnawo.html">14.&nbsp;&nbsp;Configuring JavaServer Faces Applications</a></p>
<p class="toc level2"><a href="bnaxu.html">15.&nbsp;&nbsp;Internationalizing and Localizing Web Applications</a></p>
<p class="toc level1 tocsp"><a href="bnayk.html">Part&nbsp;III&nbsp;Web Services</a></p>
<p class="toc level2"><a href="bnayl.html">16.&nbsp;&nbsp;Building Web Services with JAX-WS</a></p>
<p class="toc level2"><a href="bnazf.html">17.&nbsp;&nbsp;Binding between XML Schema and Java Classes</a></p>
<p class="toc level2"><a href="bnbdv.html">18.&nbsp;&nbsp;Streaming API for XML</a></p>
<p class="toc level2"><a href="bnbhf.html">19.&nbsp;&nbsp;SOAP with Attachments API for Java</a></p>
<p class="toc level1 tocsp"><a href="bnblr.html">Part&nbsp;IV&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbls.html">20.&nbsp;&nbsp;Enterprise Beans</a></p>
<p class="toc level2"><a href="bnbnb.html">21.&nbsp;&nbsp;Getting Started with Enterprise Beans</a></p>
<p class="toc level2"><a href="bnboc.html">22.&nbsp;&nbsp;Session Bean Examples</a></p>
<p class="toc level2"><a href="bnbpk.html">23.&nbsp;&nbsp;A Message-Driven Bean Example</a></p>
<p class="toc level1 tocsp"><a href="bnbpy.html">Part&nbsp;V&nbsp;Persistence</a></p>
<p class="toc level2"><a href="bnbpz.html">24.&nbsp;&nbsp;Introduction to the Java Persistence API</a></p>
<p class="toc level2"><a href="bnbrl.html">25.&nbsp;&nbsp;Persistence in the Web Tier</a></p>
<p class="toc level2"><a href="bnbrs.html">26.&nbsp;&nbsp;Persistence in the EJB Tier</a></p>
<p class="toc level2"><a href="bnbtg.html">27.&nbsp;&nbsp;The Java Persistence Query Language</a></p>
<p class="toc level1 tocsp"><a href="bnbwi.html">Part&nbsp;VI&nbsp;Services</a></p>
<p class="toc level2"><a href="bnbwj.html">28.&nbsp;&nbsp;Introduction to Security in the Java EE Platform</a></p>
<p class="toc level2"><a href="bnbyk.html">29.&nbsp;&nbsp;Securing Java EE Applications</a></p>
<p class="toc level2"><a href="bncas.html">30.&nbsp;&nbsp;Securing Web Applications</a></p>
<p class="toc level2"><a href="bncdq.html">31.&nbsp;&nbsp;The Java Message Service API</a></p>
<p class="toc level3"><a href="bncdr.html">Overview of the JMS API</a></p>
<p class="toc level4"><a href="bncdr.html#bncds">What Is Messaging?</a></p>
<p class="toc level4"><a href="bncdr.html#bncdt">What Is the JMS API?</a></p>
<p class="toc level4"><a href="bncdr.html#bncdu">When Can You Use the JMS API?</a></p>
<p class="toc level4"><a href="bncdr.html#bncdw">How Does the JMS API Work with the Java EE Platform?</a></p>
<p class="toc level3 tocsp"><a href="bncdx.html">Basic JMS API Concepts</a></p>
<p class="toc level4"><a href="bncdx.html#bncdy">JMS API Architecture</a></p>
<p class="toc level4"><a href="bncdx.html#bncea">Messaging Domains</a></p>
<p class="toc level5"><a href="bncdx.html#bnceb">Point-to-Point Messaging Domain</a></p>
<p class="toc level5"><a href="bncdx.html#bnced">Publish/Subscribe Messaging Domain</a></p>
<p class="toc level5"><a href="bncdx.html#bncef">Programming with the Common Interfaces</a></p>
<p class="toc level4 tocsp"><a href="bncdx.html#bnceg">Message Consumption</a></p>
<p class="toc level3 tocsp"><a href="bnceh.html">The JMS API Programming Model</a></p>
<p class="toc level4"><a href="bnceh.html#bncej">JMS Administered Objects</a></p>
<p class="toc level5"><a href="bnceh.html#bncek">JMS Connection Factories</a></p>
<p class="toc level5"><a href="bnceh.html#bncel">JMS Destinations</a></p>
<p class="toc level4 tocsp"><a href="bnceh.html#bncem">JMS Connections</a></p>
<p class="toc level4"><a href="bnceh.html#bncen">JMS Sessions</a></p>
<p class="toc level4"><a href="bnceh.html#bnceo">JMS Message Producers</a></p>
<p class="toc level4"><a href="bnceh.html#bncep">JMS Message Consumers</a></p>
<p class="toc level5"><a href="bnceh.html#bnceq">JMS Message Listeners</a></p>
<p class="toc level5"><a href="bnceh.html#bncer">JMS Message Selectors</a></p>
<p class="toc level4 tocsp"><a href="bnceh.html#bnces">JMS Messages</a></p>
<p class="toc level5"><a href="bnceh.html#bncet">Message Headers</a></p>
<p class="toc level5"><a href="bnceh.html#bncev">Message Properties</a></p>
<p class="toc level5"><a href="bnceh.html#bncew">Message Bodies</a></p>
<p class="toc level4 tocsp"><a href="bnceh.html#bncey">JMS Queue Browsers</a></p>
<p class="toc level4"><a href="bnceh.html#bncez">JMS Exception Handling</a></p>
<p class="toc level3 tocsp"><a href="bncfa.html">Writing Simple JMS Client Applications</a></p>
<p class="toc level4"><a href="bncfa.html#bncfb">A Simple Example of Synchronous Message Receives</a></p>
<p class="toc level5"><a href="bncfa.html#bncfc">Writing the Client Programs for the Synchronous Receive Example</a></p>
<p class="toc level5"><a href="bncfa.html#bncfd">Starting the JMS Provider</a></p>
<p class="toc level5"><a href="bncfa.html#bncfe">Creating JMS Administered Objects for the Synchronous Receive Example</a></p>
<p class="toc level5"><a href="bncfa.html#bncff">Compiling and Packaging the Clients for the Synchronous Receive Example</a></p>
<p class="toc level5"><a href="bncfa.html#bncfg">Running the Clients for the Synchronous Receive Example</a></p>
<p class="toc level4 tocsp"><a href="bncfa.html#bncfh">A Simple Example of Asynchronous Message Consumption</a></p>
<p class="toc level5"><a href="bncfa.html#bncfi">Writing the Client Programs for the Asynchronous Receive Example</a></p>
<p class="toc level5"><a href="bncfa.html#bncfj">Compiling and Packaging the <tt>AsynchConsumer</tt> Client</a></p>
<p class="toc level5"><a href="bncfa.html#bncfk">Running the Clients for the Asynchronous Receive Example</a></p>
<p class="toc level4 tocsp"><a href="bncfa.html#bncfl">A Simple Example of Browsing Messages in a Queue</a></p>
<p class="toc level5"><a href="bncfa.html#bncfm">Writing the Client Program for the Queue Browser Example</a></p>
<p class="toc level5"><a href="bncfa.html#bncfn">Compiling and Packaging the <tt>MessageBrowser</tt> Client</a></p>
<p class="toc level5"><a href="bncfa.html#bncfo">Running the Clients for the Queue Browser Example</a></p>
<p class="toc level4 tocsp"><a href="bncfa.html#bncfp">Running JMS Client Programs on Multiple Systems</a></p>
<p class="toc level5"><a href="bncfa.html#bncfq">Creating Administered Objects for Multiple Systems</a></p>
<p class="toc level5"><a href="bncfa.html#bncfs">Editing, Recompiling, Repackaging, and Running the Programs</a></p>
<p class="toc level5"><a href="bncfa.html#bncft">Deleting the Connection Factory and Stopping the Server</a></p>
<p class="toc level3 tocsp"><a href="bncfu.html">Creating Robust JMS Applications</a></p>
<p class="toc level4"><a href="bncfu.html#bncfv">Using Basic Reliability Mechanisms</a></p>
<p class="toc level5"><a href="bncfu.html#bncfw">Controlling Message Acknowledgment</a></p>
<p class="toc level5"><a href="bncfu.html#bncfy">Specifying Message Persistence</a></p>
<p class="toc level5"><a href="bncfu.html#bncfz">Setting Message Priority Levels</a></p>
<p class="toc level5"><a href="bncfu.html#bncga">Allowing Messages to Expire</a></p>
<p class="toc level5"><a href="bncfu.html#bncgb">Creating Temporary Destinations</a></p>
<p class="toc level4 tocsp"><a href="bncfu.html#bncgc">Using Advanced Reliability Mechanisms</a></p>
<p class="toc level5"><a href="bncfu.html#bncgd">Creating Durable Subscriptions</a></p>
<p class="toc level5"><a href="bncfu.html#bncgh">Using JMS API Local Transactions</a></p>
<div class="onpage">
<p class="toc level3 tocsp"><a href="">Using the JMS API in a Java EE Application</a></p>
<p class="toc level4"><a href="#bncgm">Using <tt>@Resource</tt> Annotations in Java EE Components</a></p>
<p class="toc level4"><a href="#bncgn">Using Session Beans to Produce and to Synchronously Receive Messages</a></p>
<p class="toc level5"><a href="#bncgo">Resource Management</a></p>
<p class="toc level5"><a href="#bncgp">Transactions</a></p>
<p class="toc level4 tocsp"><a href="#bncgq">Using Message-Driven Beans to Receive Messages Asynchronously</a></p>
<p class="toc level4"><a href="#bncgs">Managing Distributed Transactions</a></p>
<p class="toc level4"><a href="#bncgt">Using the JMS API with Application Clients and Web Components</a></p>
</div>
<p class="toc level3 tocsp"><a href="bncgu.html">Further Information about JMS</a></p>
<p class="toc level2 tocsp"><a href="bncgv.html">32.&nbsp;&nbsp;Java EE Examples Using the JMS API</a></p>
<p class="toc level2"><a href="bncih.html">33.&nbsp;&nbsp;Transactions</a></p>
<p class="toc level2"><a href="bncjh.html">34.&nbsp;&nbsp;Resource Connections</a></p>
<p class="toc level2"><a href="bncjx.html">35.&nbsp;&nbsp;Connector Architecture</a></p>
<p class="toc level1 tocsp"><a href="bnckn.html">Part&nbsp;VII&nbsp;Case Studies</a></p>
<p class="toc level2"><a href="bncko.html">36.&nbsp;&nbsp;The Coffee Break Application</a></p>
<p class="toc level2"><a href="bnclz.html">37.&nbsp;&nbsp;The Duke's Bank Application</a></p>
<p class="toc level1 tocsp"><a href="gexbq.html">Part&nbsp;VIII&nbsp;Appendixes</a></p>
<p class="toc level2"><a href="bncno.html">A.&nbsp;&nbsp;Java Encoding Schemes</a></p>
<p class="toc level2"><a href="bncnq.html">B.&nbsp;&nbsp;Preparation for Java EE Certification Exams</a></p>
<p class="toc level2"><a href="bncnt.html">C.&nbsp;&nbsp;About the Authors</a></p>
<p class="toc level1 tocsp"><a href="idx-1.html">Index</a></p>
</td>
      <td width="10px">&nbsp;</td>
      <td width="705px">
         <div class="header">
             <div class="header-links-top">
                 <a href="http://java.sun.com">java.sun.com</a> |
                 <a href="http://docs.sun.com/">docs.sun.com</a><br>
             </div> 
             <img src="graphics/tutorialBanner.gif" width="704" height="120" alt="The Java&trade; EE 5 Tutorial"/>
             <div class="header-links">
	         <a href="index.html">Home</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/download.html">Download</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/JavaEETutorial.pdf">PDF</a> |
                 <a href="http://java.sun.com/javaee/5/docs/api/index.html">API</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/faq.html">FAQ</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/search.html">Search</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/sendusmail.html">Feedback</a> |
                 <a href="http://java.sun.com/javaee/5/docs/tutorial/information/history.html">History</a>
             </div>
             <div class="navigation">
                 <a href="bncfu.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
                 <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
                 <a href="bncgu.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
             </div>
         </div>

	 <div class="maincontent">      	 
             

<a name="bncgl"></a><h3>Using the JMS API in a Java EE Application</h3>
<a name="indexterm-2946"></a><p>This section describes the ways in which using the JMS API in
a Java EE application differs from using it in a stand-alone client application:</p>
<ul><li><p><a href="#bncgm">Using <tt>@Resource</tt> Annotations in Java EE Components</a></p></li>
<li><p><a href="#bncgn">Using Session Beans to Produce and to Synchronously Receive Messages</a></p></li>
<li><p><a href="#bncgq">Using Message-Driven Beans to Receive Messages Asynchronously</a></p></li>
<li><p><a href="#bncgs">Managing Distributed Transactions</a></p></li>
<li><p><a href="#bncgt">Using the JMS API with Application Clients and Web Components</a></p></li></ul>
<p>A general rule in the Java EE platform specification applies to all Java
EE components that use the JMS API within EJB or web containers:</p><p>Application components in the web and EJB containers must not attempt to create
more than one active (not closed) <tt>Session</tt> object per connection.</p><p>This rule does not apply to application clients.</p>

<a name="bncgm"></a><h4>Using <tt>@Resource</tt> Annotations in Java EE Components</h4>
<p>When you use the <tt>@Resource</tt> annotation in an application client component, you normally
declare the JMS resource static:</p><pre>@Resource(mappedName="jms/ConnectionFactory")
private static ConnectionFactory connectionFactory;

@Resource(mappedName="jms/Queue")
private static Queue queue;</pre><p>However, when you use this annotation in a session bean, a message-driven bean,
or a web component, do <b>not</b> declare the resource static:</p><pre>@Resource(mappedName="jms/ConnectionFactory")
private ConnectionFactory connectionFactory;

@Resource(mappedName="jms/Topic")
private Topic topic;</pre><p>If you declare the resource static, runtime errors will result.</p>

<a name="bncgn"></a><h4>Using Session Beans to Produce and to Synchronously Receive Messages</h4>
<p>A Java EE application that produces messages or synchronously receives them can use
a session bean to perform these operations. The example in <a href="bncgw.html">A Java EE Application That Uses the JMS API with a Session Bean</a> uses
a stateless session bean to publish messages to a topic.</p><p>Because a blocking synchronous receive ties up server resources, it is not a
good programming practice to use such a <tt>receive</tt> call in an enterprise bean.
Instead, use a timed synchronous receive, or use a message-driven bean to receive
messages asynchronously. For details about blocking and timed synchronous receives, see <a href="bncfa.html#bncfc">Writing the Client Programs for the Synchronous Receive Example</a>.</p><p>Using the JMS API in a Java EE application is in many
ways similar to using it in a stand-alone client. The main differences are
in resource management and transactions.</p>

<a name="bncgo"></a><h5>Resource Management</h5>
<a name="indexterm-2947"></a><a name="indexterm-2948"></a><a name="indexterm-2949"></a><p>The JMS API resources are a JMS API connection and a JMS
API session. In general, it is important to release JMS resources when they
are no longer being used. Here are some useful practices to follow.</p>
<ul><li><p>If you wish to maintain a JMS API resource only for the life span of a business method, it is a good idea to close the resource in a <tt>finally</tt> block within the method.</p></li>
<li><p>If you would like to maintain a JMS API resource for the life span of an enterprise bean instance, it is a good idea to use a <tt>@PostConstruct</tt> callback method to create the resource and to use a <tt>@PreDestroy</tt> callback method to close the resource. If you use a stateful session bean and you wish to maintain the JMS API resource in a cached state, you must close the resource in a @<tt>PrePassivate</tt> callback method and set its value to <tt>null</tt>, and you must create it again in a <tt>@PostActivate</tt> callback method.</p></li></ul>


<a name="bncgp"></a><h5>Transactions</h5>
<a name="indexterm-2950"></a><p>Instead of using local transactions, you use container-managed transactions for bean methods that
perform sends or receives, allowing the EJB container to handle transaction demarcation. Because
container-managed transactions are the default, you do not have to use an annotation
to specify them.</p><p>You can use bean-managed transactions and the <tt>javax.transaction.UserTransaction</tt> interface&rsquo;s transaction demarcation methods,
but you should do so only if your application has special requirements and
you are an expert in using transactions. Usually, container-managed transactions produce the most efficient
and correct behavior. This tutorial does not provide any examples of bean-managed transactions.</p>

<a name="bncgq"></a><h4>Using Message-Driven Beans to Receive Messages Asynchronously</h4>
<a name="indexterm-2951"></a><a name="indexterm-2952"></a><p>The sections <a href="bnbmd.html">What Is a Message-Driven Bean?</a> and <a href="bncdr.html#bncdw">How Does the JMS API Work with the Java EE Platform?</a> describe how the Java EE platform supports a
special kind of enterprise bean, the message-driven bean, which allows Java EE applications
to process JMS messages asynchronously. Session beans allow you to send messages and
to receive them synchronously but not asynchronously.</p><p>A message-driven bean is a message listener that can reliably consume messages from
a queue or a durable subscription. The messages can be sent by any
Java EE component (from an application client, another enterprise bean, or a web
component) or from an application or a system that does not use
Java EE technology.</p><p><a name="indexterm-2953"></a>Like a message listener in a stand-alone JMS client, a message-driven bean contains
an <tt>onMessage</tt> method that is called automatically when a message arrives. Like a
message listener, a message-driven bean class can implement helper methods invoked by the
<tt>onMessage</tt> method to aid in message processing.</p><p>A message-driven bean, however, differs from a stand-alone client&rsquo;s message listener in the
following ways:</p>
<ul><li><p>Certain setup tasks are performed by the EJB container.</p></li>
<li><p>The bean class uses the <tt>@MessageDriven</tt> annotation to specify properties for the bean or the connection factory, such as a destination type, a durable subscription, a message selector, or an acknowledgment mode. The examples in <a href="bncgv.html">Chapter&nbsp;32, Java EE Examples Using the JMS API</a> show how the JMS resource adapter works in the Application Server.</p></li></ul>
<p>The EJB container automatically performs several setup tasks that a stand-alone client has
to do:</p>
<ul><li><p>Creating a message consumer to receive the messages. Instead of creating a message consumer in your source code, you associate the message-driven bean with a destination and a connection factory at deployment time. If you want to specify a durable subscription or use a message selector, you do this at deployment time also.</p></li>
<li><p>Registering the message listener. You must not call <tt>setMessageListener</tt>.</p></li>
<li><p><a name="indexterm-2954"></a>Specifying a message acknowledgment mode. The default mode, <tt>AUTO_ACKNOWLEDGE</tt>, is used unless it is overriden by a property setting.</p></li></ul>
<p>If JMS is integrated with the application server using a resource adapter, the
JMS resource adapter handles these tasks for the EJB container.</p><p>Your message-driven bean class must implement the <tt>javax.jms.MessageListener</tt> interface and the <tt>onMessage</tt>
method.</p><p>It may implement a <tt>@PostConstruct</tt> callback method to create a connection, and a
<tt>@PreDestroy</tt> callback method to close the connection. Typically, it implements these methods if
it produces messages or does synchronous receives from another destination.</p><p>The bean class commonly injects a <tt>MessageDrivenContext</tt> resource, which provides some additional methods
that you can use for transaction management.</p><p>The main difference between a message-driven bean and a session bean is that
a message-driven bean has no local or remote interface. Instead, it has only
a bean class.</p><p>A message-driven bean is similar in some ways to a stateless session bean:
Its instances are relatively short-lived and retain no state for a specific client.
The instance variables of the message-driven bean instance can contain some state across
the handling of client messages: for example, a JMS API connection, an open
database connection, or an object reference to an enterprise bean object.</p><p>Like a stateless session bean, a message-driven bean can have many interchangeable instances
running at the same time. The container can pool these instances to allow
streams of messages to be processed concurrently. The container attempts to deliver messages
in chronological order when it does not impair the concurrency of message processing,
but no guarantees are made as to the exact order in which messages
are delivered to the instances of the message-driven bean class. Because concurrency can
affect the order in which messages are delivered, you should write your applications
to handle messages that arrive out of sequence.</p><p>For example, your application could manage conversations by using application-level sequence numbers. An
application-level conversation control mechanism with a persistent conversation state could cache later messages
until earlier messages have been processed.</p><p>Another way to ensure order is to have each message or message
group in a conversation require a confirmation message that the sender blocks on receipt
of. This forces the responsibility for order back on the sender and more
tightly couples senders to the progress of message-driven beans.</p><p>To create a new instance of a message-driven bean, the container does the
following:</p>
<ul><li><p>Instantiates the bean</p></li>
<li><p>Performs any required resource injection</p></li>
<li><p>Calls the <tt>@PostConstruct</tt> callback method, if it exists</p></li></ul>
<p>To remove an instance of a message-driven bean, the container calls the <tt>@PreDestroy</tt>
callback method.</p><p><a href="#bncgr">Figure&nbsp;31-11</a> shows the life cycle of a message-driven bean.</p><a name="bncgr"></a><h6>Figure&nbsp;31-11 Life Cycle of a Message-Driven Bean</h6><img src="figures/ejbcon-messageDrivenBeanLifeCycle.gif" alt="Diagram showing message-driven bean life cycle"></img>

<a name="bncgs"></a><h4>Managing Distributed Transactions</h4>
<a name="indexterm-2955"></a><p>JMS client applications use JMS API local transactions (described in <a href="bncfu.html#bncgh">Using JMS API Local Transactions</a>), which
allow the grouping of sends and receives within a specific JMS session. Java
EE applications commonly use distributed transactions to ensure the integrity of accesses to external
resources. For example, distributed transactions allow multiple applications to perform atomic updates on
the same database, and they allow a single application to perform atomic updates
on multiple databases.</p><p>In a Java EE application that uses the JMS API, you can
use transactions to combine message sends or receives with database updates and other
resource manager operations. You can access resources from multiple application components within a single
transaction. For example, a servlet can start a transaction, access multiple databases, invoke
an enterprise bean that sends a JMS message, invoke another enterprise bean that
modifies an EIS system using the Connector architecture, and finally commit the transaction.
Your application cannot, however, both send a JMS message and receive a reply
to it within the same transaction; the restriction described in <a href="bncfu.html#bncgh">Using JMS API Local Transactions</a> still applies.</p><p>Distributed transactions within the EJB container can be either of two kinds:</p>
<ul><li><p><a name="indexterm-2956"></a><b>Container-managed transactions</b>: The EJB container controls the integrity of your transactions without your having to call <tt>commit</tt> or <tt>rollback</tt>. Container-managed transactions are recommended for Java EE applications that use the JMS API. You can specify appropriate transaction attributes for your enterprise bean methods.</p><p>Use the <tt>Required</tt> transaction attribute (the default) to ensure that a method is always part of a transaction. If a transaction is in progress when the method is called, the method will be part of that transaction; if not, a new transaction will be started before the method is called and will be committed when the method returns.</p></li>
<li><p><a name="indexterm-2957"></a><a name="indexterm-2958"></a><a name="indexterm-2959"></a><b>Bean-managed transactions</b>: You can use these in conjunction with the <tt>javax.transaction.UserTransaction</tt> interface, which provides its own <tt>commit</tt> and <tt>rollback</tt> methods that you can use to delimit transaction boundaries. Bean-managed transactions are recommended only for those who are experienced in programming transactions.</p></li></ul>
<p>You can use either container-managed transactions or bean-managed transactions with message-driven beans. To
ensure that all messages are received and handled within the context of a
transaction, use container-managed transactions and use the <tt>Required</tt> transaction attribute (the default) for the
<tt>onMessage</tt> method. This means that if there is no transaction in progress, a
new transaction will be started before the method is called and will be
committed when the method returns.</p><p>When you use container-managed transactions, you can call the following <tt>MessageDrivenContext</tt> methods:</p>
<ul><li><p><a name="indexterm-2960"></a><tt>setRollbackOnly</tt>: Use this method for error handling. If an exception occurs, <tt>setRollbackOnly</tt> marks the current transaction so that the only possible outcome of the transaction is a rollback.</p></li>
<li><p><a name="indexterm-2961"></a><tt>getRollbackOnly</tt>: Use this method to test whether the current transaction has been marked for rollback.</p></li></ul>
<p>If you use bean-managed transactions, the delivery of a message to the
<tt>onMessage</tt> method takes place outside the distributed transaction context. The transaction begins when
you call the <tt>UserTransaction.begin</tt> method within the <tt>onMessage</tt> method, and it ends when
you call <tt>UserTransaction.commit</tt> or <tt>UserTransaction.rollback</tt>. Any call to the <tt>Connection.createSession</tt> method must take place
within the transaction. If you call <tt>UserTransaction.rollback</tt>, the message is not redelivered, whereas
calling <tt>setRollbackOnly</tt> for container-managed transactions does cause a message to be redelivered.</p><p>Neither the JMS API specification nor the Enterprise JavaBeans specification (available from <a href="http://java.sun.com/products/ejb/">http://java.sun.com/products/ejb/</a>) specifies
how to handle calls to JMS API methods outside transaction boundaries. The Enterprise
JavaBeans specification does state that the EJB container is responsible for acknowledging a
message that is successfully processed by the <tt>onMessage</tt> method of a message-driven bean
that uses bean-managed transactions. Using bean-managed transactions allows you to process the message by
using more than one transaction or to have some parts of the message
processing take place outside a transaction context. In most cases, however, container-managed transactions
provide greater reliability and are therefore preferable.</p><p>When you create a session in an enterprise bean, the container ignores the
arguments you specify, because it manages all transactional properties for enterprise beans. It
is still a good idea to specify arguments of <tt>true</tt> and <tt>0</tt>
to the <tt>createSession</tt> method to make this situation clear:</p><pre>session = connection.createSession(true, 0);</pre><p><a name="indexterm-2962"></a><a name="indexterm-2963"></a>When you use container-managed transactions, you normally use the <tt>Required</tt> transaction attribute (the default)
for your enterprise bean&rsquo;s business methods.</p><p>You do not specify a message acknowledgment mode when you create a
message-driven bean that uses container-managed transactions. The container acknowledges the message automatically when it
commits the transaction.</p><p><a name="indexterm-2964"></a>If a message-driven bean uses bean-managed transactions, the message receipt cannot be part
of the bean-managed transaction, so the container acknowledges the message outside the transaction.</p><p>If the <tt>onMessage</tt> method throws a <tt>RuntimeException</tt>, the container does not acknowledge
processing the message. In that case, the JMS provider will redeliver the unacknowledged
message in the future.</p>

<a name="bncgt"></a><h4>Using the JMS API with Application Clients and Web Components</h4>
<a name="indexterm-2965"></a><p>An application client in a Java EE application can use the JMS
API in much the same way that a stand-alone client program does. It
can produce messages, and it can consume messages by using either synchronous receives
or message listeners. See <a href="bnbpk.html">Chapter&nbsp;23, A Message-Driven Bean Example</a> for an example of an application client that
produces messages. For an example of using an application client to produce and
to consume messages, see <a href="bnchx.html">An Application Example That Deploys a Message-Driven Bean on Two Servers</a>.</p><p>The Java EE platform specification does not impose strict constraints on how web
components should use the JMS API. In the Application Server, a web component
can send messages and consume them synchronously but cannot consume them asynchronously.</p><p>Because a blocking synchronous receive ties up server resources, it is not a
good programming practice to use such a <tt>receive</tt> call in a web component.
Instead, use a timed synchronous receive. For details about blocking and timed synchronous
receives, see <a href="bncfa.html#bncfc">Writing the Client Programs for the Synchronous Receive Example</a>.</p>
         </div>
         <div class="navigation">
             <a href="bncfu.html"><img style="padding-right: 3px" src="graphics/leftButton.gif" border="0"></a>
             <a href="sjsaseej2eet.html"><img style="padding-right: 3px" src="graphics/upButton.gif" border="0"></a>
             <a href="bncgu.html"><img style="padding-left: 3px" src="graphics/rightButton.gif" border="0"></a>
         </div>

         <div class="copyright">
      	    <p>The material in The Java&trade; EE 5 Tutorial is <a href='docinfo.html'>copyright</a>-protected and may not be published in other works without express written permission from Sun Microsystems.</p>
      	 </div>

      </td>
   </tr>
</tbody>
</table>
</body>
</html>

